package pg_repo

import (
	postgres_datasource "fiber_cli/datasources/postgres"
	pg_model "fiber_cli/models/postgres"

	"github.com/spf13/cast"
)

// 接口 用于存放函数方法
type ProductRepository interface {
	Create(product pg_model.Product) (err error)
	Delete(id uint) (err error)
	Update(product pg_model.Product) (err error)
	Find(id uint) (product pg_model.Product, err error)
	FindAndPaging(m map[string]interface{}) (count int64, productList []pg_model.Product)
}

// 结构 用于运用接口
type productRepository struct{}

// new product repo
func NewProductRepository() ProductRepository {
	return &productRepository{}
}

// 拿到postgres数据库表
var productTable = postgres_datasource.GetPostgresDB().Table("product")

// 创建product
func (n productRepository) Create(product pg_model.Product) (err error) {
	result := productTable.Create(&product)
	return result.Error
}

// 删除product
func (n productRepository) Delete(id uint) (err error) {
	var product pg_model.Product
	product.ID = id
	err = productTable.Unscoped().Delete(&product).Error
	return err
}

// 更新product
func (n productRepository) Update(product pg_model.Product) (err error) {
	result := productTable.Save(&product)
	err = result.Error
	return err
}

// 查找product
func (n productRepository) Find(id uint) (product pg_model.Product, err error) {
	err = productTable.First(&product, id).Error

	return product, err
}

// 分页查询product
func (n productRepository) FindAndPaging(m map[string]interface{}) (count int64, productList []pg_model.Product) {
	productTable.Count(&count)
	err := productTable.Limit(cast.ToInt(m["pageSize"])).Offset(cast.ToInt(m["pageNumber"]) * cast.ToInt(m["pageSize"])).Find(&productList).Error
	if err != nil {
		panic(err)
	}
	return count, productList
}
